import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Editor, EditorState, convertFromRaw } from 'draft-js';
import { styleMap, getBlockStyle } from './RichStyle';
import { RichRenderRoot } from './RichStyledComponent';
import decorator from './RichDecorator';

const SafeConvertFromRow = row => {
  let st;
  let isSafe = true;
  try {
    st = EditorState.createWithContent(convertFromRaw(row), decorator);
  } catch (e) {
    st = {};
    isSafe = false;
    console.warn('SafeConvertFromRow:', e);
  }

  return { st, isSafe };
};

export default class RichTextRender extends Component {
  constructor(props) {
    super(props);
    this.renderRefs = React.createRef();
    const row = props.data;
    const { st, isSafe } = SafeConvertFromRow(row);
    this.state = { editorState: st, editorSafe: isSafe };
  }

  render() {
    const { editorState, editorSafe } = this.state;

    if (!editorSafe) {
      return <RichRenderRoot />;
    }

    // If the user changes block type before entering any text, we can
    // either style the placeholder or hide it. Let's just hide it now.
    const className = 'Rich-render';

    return (
      <RichRenderRoot>
        <div className={className}>
          <Editor
            blockStyleFn={getBlockStyle}
            customStyleMap={styleMap}
            editorState={editorState}
            onChange={() => {
              console.log('Render');
            }}
            readOnly
            ref={this.renderRefs}
          />
        </div>
      </RichRenderRoot>
    );
  }
}

RichTextRender.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  data: PropTypes.any.isRequired
};
